<template>
  <div style="position:relative">
    <!-- :params="fetchParams" -->
    <FilterTable
      ref="table"
      :columns="columns"
      :dataSource="list"
      :height="200"
      :isColumnFilter="false"
      :isToperInfo="false"
      :isSelectColumn="false"
      :onSyncTableData="syncTableFun"
      :onCellChange="onCellChange"
      :onColumnsChange="columns => (this.columns = columns)"
    >
      <template slot="controls">
        <el-button size="small" type="primary" icon="el-icon-plus" @click="addWxxmHandle()">新增</el-button>
      </template>
    </FilterTable>
    <BaseDialog :visible.sync="visibleWxxm" title="维修项目选择" :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }" destroyOnClose>
      <AddWxxm ref="addWxxm" @closeWx="closeAddwxxm" />
    </BaseDialog>
  </div>
</template>
<script>
import AddWxxm from '../addXM/addwxxm';
import { dictionary } from '@/utils/dictMixin';
import { getRepairTypeData } from '@/api/repair/repairReception/customer';
import { detailsWxxm, getPartitionList, timeonce, getLAbourCode, getModelLabourCode } from '@/api/repair/repair/activitesManage';
let _this;
export default {
  name: 'Wxxm',
  components: {
    AddWxxm
  },
  mixins: [dictionary],
  props: ['type', 'detaildata'],
  data() {
    return {
      total: 0,
      visibleWxxm: false,
      columns: this.createTable(),
      // fetchParams: { xhrAbort: false},
      list: [],
      tableData: [],
      confirmButtonText: []
    };
  },
  created() {
    _this = this;
    _this.getLAbourCode();
    _this.timeonce();
    _this.getPartitionList();
    _this.getModelLabourCode();
    if (_this.type == 2) {
      _this.detailsWxxm();
    }
  },
  methods: {
    // 表格数据变化时
    async onCellChange(val, val2) {
      console.log(val, val2, 'val');
      console.log(val[Object.keys(val)[0]], '修改后对应的编码');
      let queryParams = { repairType: val2.REPAIR_TYPE_CODE };
      await this.getData(queryParams, res => {
        res = res.data;
        if (res && res.length > 0) {
          val2.CHARGE_PARTITION_CODE = res[0].CHARGE_PARTITION_CODE;
        }
      });
      // STD_LABOUR_HOUR收费工时
      // ASSIGN_LABOUR_HOUR派工工时
      // LABOUR_PRICE工时单价
      // LABOUR_AMOUNT工时费
      // DISCOUNT折扣率
      // LABOUR_AMOUNT_DISCOUNT折扣后工时费
      if (val2.LABOUR_PRICE != '') {
        this.list[val2.$index].LABOUR_AMOUNT = Number(this.list[val2.$index].STD_LABOUR_HOUR) * Number(val2.LABOUR_PRICE);
      }
      if (isNaN(Number(this.list[val2.$index].DISCOUNT))) {
        this.list[val2.$index].LABOUR_AMOUNT_DISCOUNT = 0;
      } else {
        this.list[val2.$index].LABOUR_AMOUNT_DISCOUNT = Number(this.list[val2.$index].LABOUR_AMOUNT) * Number(this.list[val2.$index].DISCOUNT);
      }
      if(val2.CHARGE_PARTITION_CODE == 'S' || val2.CHARGE_PARTITION_CODE == 'N'){
        val2.LABOUR_AMOUNT_DISCOUNT = 0.00;
      }
      //  这里就开始计算total   用来储存
      this.total = 0;
      this.list.forEach(x => {
        this.total = this.total + Number(x.LABOUR_AMOUNT_DISCOUNT);
      });
      this.$emit('handlewxxmTotal', this.total);
          
    },
    // 获取收费区分下拉框
    async getPartitionList() {
      const res = await getPartitionList();
      if (res.resultCode == 200) {
        this.columns.find(x => x.dataIndex === 'CHARGE_PARTITION_CODE').editItems = res.data.map(x => ({ value: x.CHARGE_PARTITION_CODE, text: x.CHARGE_PARTITION_NAME }));
      }
    },
    // 获取工时单价下拉框
    async timeonce() {
      const res = await timeonce();
      this.columns.find(x =>x.dataIndex === 'LABOUR_PRICE').editItems = res.data.map(x => ({ value: x.LABOUR_PRICE, text: x.LABOUR_PRICE }));
    },
    // 获取维修项目方法
    async detailsWxxm() {
      let res = await detailsWxxm(_this.detaildata);
      res.data.rows.forEach(x => {
        if (x.LABOUR_PRICE != null) {
          x.LABOUR_PRICE = Number(x.LABOUR_PRICE);
        } else {
          x.LABOUR_PRICE = null;
        }
        // STD_LABOUR_HOUR收费工时
        // ASSIGN_LABOUR_HOUR派工工时
        // LABOUR_PRICE工时单价
        // LABOUR_AMOUNT工时费
        // DISCOUNT折扣率
        // LABOUR_AMOUNT_DISCOUNT折扣后工时费
        if (x.LABOUR_PRICE != '' && x.LABOUR_PRICE != null && x.LABOUR_PRICE != undefined) {
          x.LABOUR_AMOUNT = Number(x.STD_LABOUR_HOUR) * Number(x.LABOUR_PRICE);
        }
        if (isNaN(Number(x.DISCOUNT))) {
          x.LABOUR_AMOUNT_DISCOUNT = 0;
        } else {
          x.LABOUR_AMOUNT_DISCOUNT = Number(x.LABOUR_AMOUNT) * Number(x.DISCOUNT);
        }
        if (x.LABOUR_PRICE === 0) {
          x.LABOUR_PRICE = '';
        }
        if(x.CHARGE_PARTITION_CODE == 'S'||x.CHARGE_PARTITION_CODE == 'N'){
          x.LABOUR_AMOUNT_DISCOUNT = 0;
        }
      });
      _this.$refs.table.$refs.pageTable.EXECUTE_INSERT(res.data.rows);
    },
    closeAddwxxm(val) {
      if (val != false) {
        // let pd1 = false
        // let pd2 = false
        // if (this.list.length>0){
        //   this.list.forEach(x => {
        //     if (x.MODEL_LABOUR_CODE == val[0].MODEL_LABOUR_CODE) {
        //             pd1 = true
        //     }
        //     if (x.LABOUR_CODEF == val[0].LABOUR_CODEF) {
        //             pd2 = true
        //     }
        //     })
        // }
        // if (pd1&&pd2){
        //   this.$notify.error({
        //     title: '错误',
        //     message: '请勿重复提交'
        //   });
        //   return
        // }
        this.visibleWxxm = false;
        val[0].DISCOUNT = 1;
        let UID = '';
        let LABOUR_CODE = '';
        if (val) {
          for (const item of val) {
            // item.DISCOUNT = 1;
            // item.LABOUR_PRICE = this.labourPrice || 0;
            // item.LABOUR_AMOUNT = (item.STD_LABOUR_HOUR * item.LABOUR_PRICE).toFixed(2); //parseFloat
            // item.RECEIVE_AMOUNT = (item.LABOUR_AMOUNT * item.DISCOUNT).toFixed(2);
            // item.DISCOUNT_AMOUNT = (item.LABOUR_AMOUNT - item.RECEIVE_AMOUNT).toFixed(2);
            if (!item.UID_HIDDEN) {
              item.UID_HIDDEN = item._uid;
              UID = item._uid;
            }
            LABOUR_CODE = item.LABOUR_CODE;
            item.MODEL_LABOUR_NAME = item.MODEL_LABOUR_CODE;
          }
          this.$refs.table.$refs.pageTable.EXECUTE_INSERT(val);
        }
        //  这里就开始计算total   用来储存
        this.total = 0;
        this.list.forEach(x => {
          this.total = this.total + Number(x.LABOUR_AMOUNT_DISCOUNT);
        });
        this.$emit('handlewxxmTotal', this.total);
      } else if (val == false) {
        this.visibleWxxm = false;
      }
    },
    // 项目维修代码下拉框获取方法
    async getLAbourCode() {
      const res = await getLAbourCode();
      if (res.resultCode == 200) {
        this.columns.find(x => x.dataIndex === 'REPAIR_TYPE_CODE').editItems = res.data.map(x => ({ value: x.REPAIR_TYPE_CODE, text: x.REPAIR_TYPE_NAME }));
      }
    },
    async getModelLabourCode() {
      const res = await getModelLabourCode();
      if (res.resultCode == 200) {
        this.columns.find(x => x.dataIndex === 'MODEL_LABOUR_NAME').editItems = res.data.map(x => ({ value: x.SERIES_ID, text: x.MODEL_LABOUR_NAME }));
      }
    },
    ceshi(val) {
      _this.$emit('changeone', _this.list);
    },
    async getData(queryParams, callback) {
      let res = await getRepairTypeData(queryParams);
      callback(res);
    },
    // 传给父组件的数据
    syncTableFun(val) {
      val.forEach(x => {
        if (x.REPAIR_TYPE_CODE && x.REPAIR_TYPE_CODE != '0') {
          let queryParams = { repairType: x.REPAIR_TYPE_CODE };
          this.getData(queryParams, res => {
            res = res.data;
            if (res && res.length > 0) {
              this.$emit('refershSfqfInfo', x);
              console.log('项目维修类型请求收费', res);
            }
          });
        } else {
          x.CHARGE_PARTITION_CODE = '';
        }
      });

      // delete val.dataMark;
      this.$emit('syncTablelist', val);
      this.tableData = val;
    },
    addWxxmHandle() {
      this.visibleWxxm = true;
    },
    createTable() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          fixed: 'left',
          width: 70,
          render: props => {
            // return <span>{props.row.index + 1}</span>;
            return <span>{props.$index + 1}</span>;
          }
        },
        {
          title: '操作',
          fixed: 'left',
          dataIndex: 'column-action',
          render: props => {
            return (
              <el-button size="mini" type="text" onClick={() => this.delete(props.row)}>
                删除
              </el-button>
            );
          }
        },
        {
          title: '项目车系',
          dataIndex: 'MODEL_LABOUR_NAME',
          sorter: true,
          editable: false,
          editType: 'select',
          editItems: []
        },
        {
          title: '维修项目代码',
          dataIndex: 'LABOUR_CODEF',
          sorter: true
        },
        {
          title: '维修项目名称',
          dataIndex: 'LABOUR_NAME',
          sorter: true
        },
        {
          title: '项目维修类型',
          dataIndex: 'REPAIR_TYPE_CODE',
          sorter: true,
          editable: true,
          editType: 'select',
          editItems: []
          // render: props => {
          //   return <span>{this.func(props.row.REPAIR_TYPE_CODE,5)}</span>;
          //   }
        },

        {
          title: '收费区分',
          dataIndex: 'CHARGE_PARTITION_CODE',
          sorter: true,
          filterItems: [],
          editable: false,
          editType: 'select',
          editRequired: true,
          editItems: []
          // render: props => {
          //   return <span>{this.func(props.row.CHARGE_PARTITION_CODE,6)}</span>;
          //   }·
        },
        {
          title: '收费工时',
          dataIndex: 'STD_LABOUR_HOUR',
          sorter: true
        },
        {
          title: '派工工时',
          dataIndex: 'ASSIGN_LABOUR_HOUR',
          sorter: true,
          summation: true
        },
        {
          title: '工时单价',
          dataIndex: 'LABOUR_PRICE',
          sorter: true,
          summation: true,
          editable: true,
          editType: 'select',
          editItems: []
        },
        {
          title: '工时费',
          dataIndex: 'LABOUR_AMOUNT',
          sorter: true,
          precision: 2,
          summation: true
        },
        {
          title: '折扣率',
          dataIndex: 'DISCOUNT',
          sorter: true,
          editable: true,
          editType: 'number',
          max: 1,
          min: 0,
          precision: 2
        },
        {
          title: '折扣后工时费',
          dataIndex: 'LABOUR_AMOUNT_DISCOUNT',
          sorter: true,
          precision: 2,
          summation: true
        }
      ];
    },
    // 维修项目表单数据删除
    delete(val) {
      this.$confirm('此操作将删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.$refs.table.$refs.pageTable.EXECUTE_DELETE([val]);
          //  这里就开始计算total   用来储存
          this.total = 0;
          this.list.forEach(x => {
            this.total = this.total + Number(x.LABOUR_AMOUNT_DISCOUNT);
          });
          // 再写个方法传删除数据
          if (val.ITEM_ID != null && val.ITEM_ID != '' && val.ITEM_ID != undefined) {
            this.$emit('handleDeleted', val);
          }
          this.$emit('handlewxxmTotal', this.total);
        })
        .catch(() => {});
    },
    async getFwhdWxxmList(row) {
      const res = await getFwhdWxxmList(row, {
        creditTimes: 1.0,
        afterlabour: 0,
        zkAmountLabour: 0,
        afterDiscountAmountPart: 0,
        zkAmountPart: 0,
        fag: 'U',
        labourList: '',
        partList: '',
        subjoinList: '',
        modelList: '',
        vehicleList: '',
        order: 'asc',
        limit: 10,
        offset: 0,
        dmsFuncId: 35100010,
        _: 1565681747515
      });
      this.list = res.rows;
    },
    async getFwhdSfList() {
      const res = await getFwhdSfList();
      this.columns[6].filterItems = res.map(x => ({ value: x.CHARGE_PARTITION_CODE, text: x.CHARGE_PARTITION_NAME }));
    },
    async getFwhdWxlxList() {
      const res = await getFwhdWxlxList();
      this.columns[5].filterItems = res.map(x => ({ value: x.REPAIR_TYPE_CODE, text: x.REPAIR_TYPE_NAME }));
    },
    async getFwhdGsdjList() {
      const res = await getFwhdGsdjList();
      this.columns[9].filterItems = res.map(x => ({ value: x.LABOUR_PRICE_CODE, text: x.LABOUR_PRICE }));
    },
    func(val, num) {
      if (val) {
        const res = this.columns[num].filterItems.find(x => x.value == val);
        return res.text;
      }
    }
  }
};
</script>
